import React, { memo, useRef, useState } from "react";
import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";

import { Input, Divider, Button, message } from "antd";
import { LeftOutlined, CameraFilled } from "@ant-design/icons";

import { UpdateProfileWrapper } from "./style";

// 网络请求
import { updateUserInfo } from "@/services";
import axios from "axios";

// 引入更新用户信息的action
import { setNewUserInfoAction } from "@/pages/login/store/actionCreators";

// 虚拟头像
import touxiang from "@/assets/img/touxiang.jpg";

export default memo(function UpdateProfile(props) {
  const { avatar, nickName, schoolId, content, userId } = props.location.state;
  const history = useHistory();
  const inputRef = useRef();
  const dispatch = useDispatch();
  // 受控组件区域
  const [imgUrl, setImgUrl] = useState(avatar);
  const [nickname, setNickname] = useState(nickName);
  const [conTent, setConTent] = useState(content);
  const [schoolID, setSchoolID] = useState(schoolId);
  const [avatarBuffer, setAvatarBuffer] = useState(avatar);

  const handleNickNameInput = (e) => {
    setNickname(e.target.value);
  };
  const handleContentInput = (e) => {
    setConTent(e.target.value);
  };
  const handleSchoolIDInput = (e) => {
    setSchoolID(e.target.value);
  };

  const jumpToProfilePage = () => {
    history.goBack();
  };

  // 处理上传图片
  const handleUpload = () => {
    const file = inputRef.current.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setImgUrl(reader.result);
      let formData = new FormData();
      formData.append("file", file);
      axios
        .post("http://192.168.232.202:8001/eduoss/fileoss", formData, {
          headers: {
            "Content-Type":
              "multipart/form-data; boundary=----WebKitFormBoundaryUPpZmJyZ2YUuTb55",
          },
        })
        .then((res) => {
          setAvatarBuffer(res.data);
        });
    };
  };

  // 保存按钮
  const handleSubmit = () => {
    const data = {
      userId,
      avatar: avatarBuffer,
      nickName: nickname,
      content: conTent,
      schoolId: schoolID,
    };
    updateUserInfo(data).then((res) => {
      console.log(res);
      if ((res.code = 200)) {
        message.success({
          content: "修改成功！",
          duration: 1,
          style: {
            marginTop: "40vh",
          },
        });
        dispatch(setNewUserInfoAction(userId));
        // 跳转到个人页面 并刷新页面信息
        setTimeout(() => {
          history.goBack();
        }, 1000);
      } else {
        message.error({
          content: "修改失败！",
          duration: 1,
          style: {
            marginTop: "40vh",
          },
        });
      }
    });
  };

  return (
    <UpdateProfileWrapper>
      <div className="header">
        <i style={{ fontSize: "18px" }} onClick={jumpToProfilePage}>
          <LeftOutlined />
        </i>
        <span className="title">编辑资料</span>
        <i style={{ visibility: "hidden" }}>
          <LeftOutlined />
        </i>
      </div>
      <div className="body">
        <div className="avatar">
          <img alt="" src={imgUrl ? imgUrl : touxiang} />
          <input
            type="file"
            ref={inputRef}
            onChange={handleUpload}
            accept="image/*"
            hidden
          />
          <i onClick={(e) => inputRef.current.click()} className="upload-icon">
            <CameraFilled style={{ fontSize: 20 }} />
          </i>
        </div>
        <Input
          value={nickname}
          onChange={handleNickNameInput}
          prefix="昵称"
          defaultValue="Jimee_"
          bordered={false}
        />
        <Divider />
        <Input
          value={conTent}
          onChange={handleContentInput}
          prefix="个人简介"
          defaultValue="没毛病"
          bordered={false}
        />
        <Divider />
        <Input
          value={schoolID}
          onChange={handleSchoolIDInput}
          prefix="学校认证"
          defaultValue="spwu"
          bordered={false}
        />
        <Divider />
      </div>
      <div className="footer">
        <Button
          shape="round"
          danger
          type="primary"
          block
          onClick={handleSubmit}
        >
          保存
        </Button>
      </div>
    </UpdateProfileWrapper>
  );
});
